<template>
  <div>
    <AlNavBar @onClickLeft="back" :title="item.content.course.data[0].name"
              :settingRight="true"
              @onClickRight="onClickRight"
              icon="icon-setting"/>


    <div class="content">

      <van-form>
        <van-field
            v-model="courseInfo.address"
            name="签到地址名"
            label="签到地址名"
            placeholder="签到地址名"
        />
      </van-form>

      <div class="date">
        <van-collapse v-model="activeName" accordion>
          <van-collapse-item name="1">
            <template #title>
              <i class="iconfont icon-time-clock"></i>日期/时间 选择
            </template>
            <div class="date1">
              <van-grid
                  :column-num="7"
                  :border="false"
                  :icon-size="10">
                <van-grid-item v-for="(item,iStep) in 7" >
                  <i class="iconfont" @click="days(iStep)" :class="dayIds[iStep]?dateIcon:''"><span
                      style="font-size: 15px" :class="ins===iStep?'strong':''">{{chChars[iStep]}}</span></i>
                </van-grid-item>
              </van-grid>
            </div>

            <div class="center-text">
              <i v-show="dayIds[ins]" class="iconfont icon-bofang" @click="sDays(ins)">星期{{ chChars[ins] }}</i>
              <i v-show="!dayIds[ins]" class="iconfont icon-zanting" @click="sDays(ins)">星期{{ chChars[ins] }}</i>
            </div>

            <div class="date2">
              <van-grid
                  :column-num="2"
                  :border="false">
                <van-grid-item>
                  <i class="iconfont" :class="dayIds[ins]?'icon-watch':'icon-padlock'"
                     @click="timeShow(ins,'start',startTimeShow)">
                    开始时间 {{ startTime[ins] == null ? '(未配置)' : startTime[ins] }}
                  </i>
                  <van-popup
                      v-model="startTimeShow"
                      position="bottom"
                      :style="{ height: '50%' }"
                  >
                    <van-datetime-picker
                        v-model="startTime[ins]"
                        type="time"
                        cancel-button-text=" "
                        confirm-button-text="确认"
                        @confirm="timeShow(ins,'start',startTimeShow)"
                        title="开始时间"
                        :min-hour="6"
                        :max-hour="22"
                    />
                  </van-popup>
                </van-grid-item>

                <van-grid-item>
                  <i class="iconfont" :class="dayIds[ins]?'icon-watch':'icon-padlock'"
                     @click="timeShow(ins,'end',endTimeShow)">
                    结束时间 {{ endTime[ins] == null ? '(未配置)' : endTime[ins] }}
                  </i>
                  <van-popup
                      v-model="endTimeShow"
                      position="bottom"
                      :style="{ height: '50%' }"
                  >
                    <van-datetime-picker
                        v-model="endTime[ins]"
                        type="time"
                        cancel-button-text=" "
                        confirm-button-text="确认"
                        @confirm="timeShow(ins,'end',endTimeShow)"
                        title="结束时间"
                        :min-hour="6"
                        :max-hour="22"
                    />
                  </van-popup>

                </van-grid-item>
              </van-grid>

            </div>
          </van-collapse-item>
        </van-collapse>
      </div>


      <van-cell @click="showMap">
        <template #label>
          <i class="iconfont icon-daohang"></i>{{ labels }}
        </template>

        <template #title>
          <i class="iconfont icon-ditu"></i>
          地址配置<span class="status">{{ title }}</span>
        </template>

        <template #right-icon>
          <i v-show="icon" class="iconfont icon-cok"></i>
        </template>
      </van-cell>

      <div>
        <mMap :width="350" :height="290" ref='ch' v-show="show"/>
        <van-button @click="getPosition" v-show="show">
          选择此地址
        </van-button>
        <van-button @click="put" color="black">
          保存
        </van-button>
      </div>

    </div>


  </div>
</template>

<script>
import {putCourse, getOne} from "@/api/app/chaoxing"
import AlNavBar from "@/components/AlNavBar";
import AlCell from "@/components/AlCell";
import {mapState} from "vuex";
import mMap from "@/components/Mmap";
import {Toast} from 'vant';

export default {
  name: "Setting",
  components: {AlNavBar, AlCell, mMap},
  data() {
    return {
      chChars: ['日', '一', '二', '三', '四', '五', '六'],
      item: {},
      dayIds: [],
      startTime: [],
      endTime: [],
      courseInfo: {
        userId: null,
        classId: null,
        courseId: null,
        latitude: null,
        longitude: null,
        address: null,
        days: null
      },
      show: false,
      icon: false,
      dateIcon: 'icon-ok',
      startTimeShow: false,
      endTimeShow: false,
      activeName: 1,
      ins: 1
    }
  },
  created: function () {
    this.item = this.$route.params.item;
    this.courseInfo.userId = this.userInfo.id;
    this.courseInfo.classId = this.item.key;
    this.courseInfo.courseId = this.item.content.course.data[0].id;

    getOne(this.userInfo.id, this.courseInfo).then(res => {
      if (res.data != null) {
        this.courseInfo = res.data;

        this.icon = this.courseInfo.latitude != null && this.courseInfo.longitude != null;

        if (this.courseInfo.days != null) {
          let day = this.courseInfo.days.split(';');

          day.forEach(d => {
            let ds = d.substring(2).split('-');
            let k = parseInt(d[0]);
            let op = d[1];
            if (op === '@') {
              this.dayIds[k] = true;
            }
            this.startTime[k] = ds[0];
            this.endTime[k] = ds[1];
          })
        }
      } else {
        this.icon = false;
      }
    })

  },
  methods: {
    back() {
      this.$router.push('/space/app/chaoxing/course/setting')
    },
    onClickRight() {
      this.$router.push('/space/app/chaoxing')
    },
    put() {
      let str = '';
      for (let i = 0; i < 7; i++) {
        if (this.dayIds[i]) {
          str = str + i + '@' + this.startTime[i] + '-' + this.endTime[i] + ';';
        } else {
          if (this.checkTime(false, this.startTime[i], this.endTime[i])) {
            str = str + i + '#' + this.startTime[i] + '-' + this.endTime[i] + ';';
          }
        }
      }
      str = str.substring(0, str.length - 1);

      this.courseInfo.days = str;
      putCourse(this.userInfo.id, this.courseInfo).then(res => {
        if (res.success) {
          Toast({
            message: '保存成功',
            className: 'iconfont icon-ok',
          });
        }
      })
    },
    getPosition() {
      this.courseInfo.longitude = this.$refs.ch.lng;
      this.courseInfo.latitude = this.$refs.ch.lat;

      this.icon = this.courseInfo.latitude != null && this.courseInfo.longitude != null;
      if (this.icon) {
        Toast({
          message: '选择成功~',
          className: 'iconfont icon-ok',
        });
      } else {
        Toast({
          message: '选择失败',
          className: 'iconfont icon-error',
        });
      }
    },
    showMap() {
      this.show = !this.show;
    },
    days(data) {
      this.ins = data;
    },
    timeShow(ins, op, item) {
      if (this.dayIds[ins]) {
        return;
      }
      if (op === 'start') {
        this.startTimeShow = !item;
      } else {
        this.endTimeShow = !item;
      }
    },
    /**
     * 存储时间，同时判断开始和结束时间是否规范(后端对于不符合规范的时间直接舍弃)
     * @param data
     */
    sDays(data) {
      if (!this.dayIds[data]) {

        if (this.checkTime(true, this.startTime[data], this.endTime[data])) {
          Toast({
            message: '开启成功',
            className: 'iconfont icon-ok',
            duration: 300
          });
        } else {
          return;
        }

      } else {
        Toast({
          message: '关闭成功',
          className: 'iconfont icon-ok',
          duration: 300
        });
      }
      this.$set(this.dayIds, data, !this.dayIds[data])
    },
    /**
     * 用于检查时间格式是否正确
     * @param op
     * @param startTime
     * @param endTime
     * @returns {boolean}
     */
    checkTime(op, startTime, endTime) {
      if (startTime == null || endTime == null) {
        if (op) {
          Toast({
            message: '开启和结束时间未填写',
            className: 'iconfont icon-error',
            duration: 1000
          });
        }
        return false;
      }
      let st = startTime.split(':');
      let et = endTime.split(':');
      if (parseInt(st[0]) > parseInt(et[0])) {
        if (op) {
          Toast({
            message: '保存失败，请检查时间是否符合格式 (时)',
            className: 'iconfont icon-error',
          });
        }
        return false;
      } else {
        if (st[0] === et[0] && parseInt(st[1]) > parseInt(et[1])) {
          if (op) {
            Toast({
              message: '保存失败，请检查时间是否符合格式 (分)',
              className: 'iconfont icon-error',
            });
          }
          return false;
        }
        return true;
      }
    }

  },
  computed: {
    ...mapState(['userInfo']),
    title() {
      if (this.icon) {
        return '已配置';
      } else {
        return '未配置';
      }
    },
    labels() {
      if (this.show) {
        return "(点击关闭地图)";
      } else {
        return "(点击打开地图)";
      }
    }
  }
}
</script>

<style lang="less">
.content {
  padding: 0 3px 0 3px;
  margin-top: 5px;

  .van-cell {
    border-radius: 15px;
    margin: 3px 0 3px 0;

    .status {
      font-weight: 200;
    }
  }

  .strong {
    color: #00b8d4;
    font-weight: 500;
  }

  .van-collapse-item__title {
    margin: 0;
  }

  .van-collapse-item__content {
    border-radius: 10px;
    padding: 0;
  }

  .van-grid-item {
    height: 44px;
  }

  .date {
    margin: 3px 0 0 0;
  }

  .van-grid-item__content--center {
    height: 40px;
    border-radius: 20px;
  }

  .van-form {
    margin-top: 3px;
  }

  .van-button {
    margin: 5px 10px 5px 10px;
    border-radius: 15px;
  }

  .iconfont.icon-bofang {
    color: @success-color;
    font-size: 10px;
  }

  .iconfont.icon-zanting {
    color: @stop-color;
    font-size: 10px;
  }

  .iconfont.icon-cok {
    margin: auto;
    font-size: 15px;
    color: @success-color;
  }

  .iconfont.icon-ok {
    margin: auto;
  }

  .iconfont.icon-bottom {
    font-size: 10px;
  }

  .iconfont.icon-watch {
    font-size: 10px;
    color: @assist-color;
  }

  .iconfont.icon-padlock {
    font-size: 10px;
    color: @main-color;
  }

  .iconfont.icon-time-clock {
    float: left;
  }

  .iconfont.icon-ditu {
    float: left;
  }

}

</style>